#include "SelectionMaterialSwitcher.h"

SelectionMaterialSwitcher::SelectionMaterialSwitcher() : mLastTechnique(0)
{
	mCurrentColor = ColourValue(0.0, 0.0, 0.0);
}

SelectionMaterialSwitcher::~SelectionMaterialSwitcher()
{
}

Technique *SelectionMaterialSwitcher::handleSchemeNotFound(unsigned short schemeIndex, const Ogre::String &schemeName,
        Ogre::Material *originalMaterial, unsigned short lodIndex,
        const Ogre::Renderable *rend)
{
	if (rend)
		{

			std::vector<Renderable*>::iterator it = mBlackList.begin();
			for(; it!=mBlackList.end(); ++it)
				{
					Ogre::Renderable* b = static_cast<Ogre::Renderable*>(*it);
					if(b==rend)
						{

							const SubEntity *subEntity = static_cast<const SubEntity *>(rend);
//							ResourcePtr res = MaterialManager::getSingleton().load("PlainColorNoCull", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
							ResourcePtr res = MaterialManager::getSingleton().load("PlainColorDepthOff", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
							mLastTechnique = static_cast<MaterialPtr>(res)->getTechnique(0);

							getNextColor();
							const_cast<SubEntity *>(subEntity)->setCustomParameter(1, Vector4(mCurrentColor.r, mCurrentColor.g, mCurrentColor.b, 1.0));

							mLastEntity = subEntity->getParent()->getName();
							mColorDict[mCurrentColor] = mLastEntity;

							return mLastTechnique;
						}
				}

			if (typeid(*rend) == typeid(SubEntity))
				{
					const SubEntity *subEntity = static_cast<const SubEntity *>(rend);
					if (mLastEntity == subEntity->getParent()->getName())
						{
							const_cast<SubEntity *>(subEntity)->setCustomParameter(1, Vector4(mCurrentColor.r, mCurrentColor.g, mCurrentColor.b, 1.0));
						}
					else
						{
							ResourcePtr res = MaterialManager::getSingleton().load("PlainColor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
							mLastTechnique = static_cast<MaterialPtr>(res)->getTechnique(0);

							getNextColor();
							const_cast<SubEntity *>(subEntity)->setCustomParameter(1, Vector4(mCurrentColor.r, mCurrentColor.g, mCurrentColor.b, 1.0));

							mLastEntity = subEntity->getParent()->getName();
							mColorDict[mCurrentColor] = mLastEntity;
						}
					return mLastTechnique;
				}
		}
	return 0;
}

const String &SelectionMaterialSwitcher::getEntityName(const Ogre::ColourValue &color) const
{
	ColorMapConstIter iter = mColorDict.find(color);
	if (iter != mColorDict.end())
		return (*iter).second;
	else
		return mEmptyString;
}

void SelectionMaterialSwitcher::getNextColor()
{
//  ARGB color = mCurrentColor.getAsARGB();
//  color++;
//  mCurrentColor.setAsARGB(color);
	mCurrentColor.setAsARGB(Ogre::Math::UnitRandom()*0x00FFFFFF + 0xFF000000);
}

void SelectionMaterialSwitcher::reset()
{
	mCurrentColor = ColourValue(0.0, 0.0, 0.0);
	mLastEntity.clear();
	mColorDict.clear();
}
